// pages/home/home.js
import {
  request
} from "../../request";
import {
  regeneratorRuntime
} from "../../libs/runtime/runtime";
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    inputShowed: false,
    user: wx.getStorageSync('user'),
    img1: [],
    img2: [],
    currentindex: 0,
    NavTab: ['推荐', '早餐', '午餐', '国培大厦', '西门'],
    shoucang: {},
    shoucang1: {},
  },
  HomeData_1: [],
  HomeData_2: [],
  onLoad: function () {
    //this.getShouCang();
    this.sX()
    const HomeData1 = wx.getStorageSync("HomeData1");
    const HomeData2 = wx.getStorageSync("HomeData2");
    if (!HomeData1) {
      console.log('获取接口数据');
      this.gethomedata();
    } else {
      if (Date.now() - HomeData1.time > 1000 * 600) {
        this.gethomedata();
      } else {
        console.log('使用本地storage数据')
        this.HomeData_1 = HomeData1.data
        this.HomeData_2 = HomeData2.data
        let Shoplist1 = this.HomeData_1
        let Shoplist2 = this.HomeData_2
        this.setData({
          img1: Shoplist1,
          img2: Shoplist2
        })
      }
    }
    //上传微信openid 获取服务端openid
    wx.checkSession({
      success: (res) => {
        console.log('已登录');
        wx.login({
          success: (res) => {
            console.log(res.code);
            wx.request({
              url: 'https://fourgoldhua.cn/wxgetId',
              method: "POST",
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: (res) => {
                wx.setStorageSync('openid', res.data)
                console.log(res.data)
              },
              fail: () => {
                console.log('获取失败')
              }
            })
          }
        })
      },
      fail: (res) => {
        console.log('已登录');
        wx.login({
          success: (res) => {
            console.log(res.code);
            wx.request({
              url: 'https://fourgoldhua.cn/wxgetId',
              method: "POST",
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: (res) => {
                wx.setStorageSync('openid', res.data)
                console.log(res.data)
              },
              fail: () => {
                console.log('获取失败')
              }
            })
          }
        })
      }
    })
  },
  onShow: function () {
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        hasUserInfo: true
      })
    }
  },
  //搜索回调函数
  searchList(ev) {
    let likeFlag = false; //标志，避免多次发请求
    //避免多次点击
    if (likeFlag === true) {
      return false;
    }
    if (!ev.detail.detail.value.trim())
      return
    this.setData({
      searchstr: ev.detail.detail.value
    })
    this.getSearchData(this.data.searchstr)
  },
  //下拉刷新函数
  onPullDownRefresh() {
    let index = this.data.currentindex;
    if (index == 0) {
      this.gethomedata()
    } else {
      if (index == 1 || index == 2) {
        this.getOtherHomea(this.data.NavTab[index])
      } else {
        this.getOtherHomeb(this.data.NavTab[index])
      }
    }
    wx.stopPullDownRefresh()
  },
  //搜索回调
  endsearchList() {
    console.log(this.data.searchstr, '搜索回调函数')
    this.getSearchData(this.data.searchstr)
  },
  //获取搜索数据
  async getSearchData(e) {
    if (e) {
      const res = await request({
        url: '/shuju/ss',
        data: {
          text: e
        }
      });
      // 数据去重
      var hash = [];
      var res1 = res.reduce(function (pre, cur) {
        hash[cur['share_id']] ? '' : hash[cur['share_id']] = true && pre.push(cur);
        return pre;
      }, []);
      let img3 = [];
      let img4 = [];
      for (let i in res1) {
        if (i % 2 === 0)
          img3.push(res1[i])
        else
          img4.push(res1[i])
      }
      if (this.data.currentindex != 0) {
        this.setData({
          currentindex: 0
        })
      }
      this.setData({
        img1: img3,
        shoucang: img3,
        shoucanj: img4,
        img2: img4
      });
      console.log(res)
      console.log(res1)
    }
  },
  // 取消搜索
  cancelsearch() {
    this.setData({
      searchstr: ''
    })
    this.gethomedata();
  },
  //清空搜索框
  activity_clear(e) {
    this.setData({
      searchstr: ''
    })
    this.gethomedata();
  },
  //tab框
  ChangeNavtab: function (e) {
    let likeFlag = false; //标志，避免多次发请求
    //避免多次点击
    if (likeFlag === true) {
      return false;
    }
    let index = e.currentTarget.dataset.index
    this.setData({
      currentindex: index
    })
    if (index == 0) {
      const HomeData1 = wx.getStorageSync("HomeData1");
      const HomeData2 = wx.getStorageSync("HomeData2");
      if (!HomeData1) {
        console.log('获取接口数据');
        this.gethomedata();
      } else {
        if (Date.now() - HomeData1.time > 1000 * 600) {
          this.gethomedata();
        } else {
          console.log('使用本地storage数据')
          this.HomeData_1 = HomeData1.data
          this.HomeData_2 = HomeData2.data
          let Shoplist1 = this.HomeData_1
          let Shoplist2 = this.HomeData_2
          this.setData({
            img1: Shoplist1,
            img2: Shoplist2
          })
        }
      }
    } else {
      if (index == 1 || index == 2) {
        this.getOtherHomea(this.data.NavTab[index])
      } else {
        this.getOtherHomeb(this.data.NavTab[index])
      }
    }
  },
  // 跳转到详情页
  jumpdetail1: function (e) {
    wx.navigateTo({
      url: `/pages/detail1/detail1?idx=${e.currentTarget.dataset.id}`,
    })
  },
  //获取第0页面数据
  async gethomedata() {
    const res = await request({
      url: '/shuju/shouye'
    });
    console.log(res)
    let img3 = [];
    let img4 = [];
    for (let i in res) {
      if (i % 2 === 0)
        img3.push(res[i])
      else
        img4.push(res[i])
    }
    this.setData({
      img1: img3,
      img2: img4
    });
    console.log(res);
    console.log("这个是页面的长度" + res.length)
    wx.setStorageSync("HomeData1", {
      time: Date.now(),
      data: img3
    });
    wx.setStorageSync("HomeData2", {
      time: Date.now(),
      data: img4
    });
  },
  // 获取12页面数据
  async getOtherHomea(e) {
    const res = await request({
      url: '/shuju/fenlei',
      data: {
        food: e
      }
    });
    let img3 = [];
    let img4 = [];
    for (let i in res) {
      if (i % 2 === 0)
        img3.push(res[i])
      else
        img4.push(res[i])
    }
    this.setData({
      img1a: img3,
      img2a: img4
    });
    console.log("这个是1/2页面的长度" + res.length)
  },
  //获取34页面数据
  async getOtherHomeb(e) {
    const res = await request({
      url: '/shuju/fenlei',
      data: {
        addr: e
      }
    });
    let img3 = [];
    let img4 = [];
    for (let i in res) {
      if (i % 2 === 0)
        img3.push(res[i])
      else
        img4.push(res[i])
    }
    this.setData({
      img1b: img3,
      img2b: img4
    });
    console.log("这个是3/4页面的长度" + res.length)
  },
  jumpadd: function () {
    if(wx.getStorageSync('userInfo') === ''){
      wx.showModal({
        title: '您还未登录',
        content: '请点击确定跳转登录',
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/add1/add1',
      })
    }
  },
  async sX() {
    const res = await request({
      url: '/shuju/sx',
    });
    if (res.data === 1) {
      this.setData({
        sx: true
      })
    }
  },
  //获取用户身份信息
  getUserProfile(e) {
    //console.log(e)
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          hasUserInfo: true
        })
        wx.setStorageSync('userInfo', res.userInfo);
        wx.request({
          method: 'POST',
          url: `https://fourgoldhua.cn/aes-test/${wx.getStorageSync('openid')}`,
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            username: wx.getStorageSync('userInfo').nickName,
            avatarUrl: wx.getStorageSync('userInfo').avatarUrl
          },
          success: (res) => {
            console.log('上传个人信息成功')
          },
          fail: () => {
            console.log('上传个人信息失败')
          }
        })
      }
    })
  },
})